<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小瑞 - 宠物助手</title>
    <link rel="stylesheet" href="/static/styles.css">
</head>
<body>
    <h1>小瑞 - 宠物助手</h1>
    <div class="chat-container" id="chat-container">
        <!-- Chat messages will be added here -->
    </div>
    <div class="input-container">
        <select class="mode-select" id="mode-select">
            <option value="ali-bailianyun">阿里云百炼</option>
            <option value="nvidia">英伟达</option>
            <option value="local-ollama">本地Ollama</option>
        </select>
        <div class="input-wrapper">
            <input type="text" id="message-input" placeholder="输入你的问题..." 
                   aria-label="输入消息" aria-describedby="send-button" 
                   maxlength="200" />
            <div class="character-count" id="character-count">0/200</div>
        </div>
        <button onclick="sendMessage()" id="send-button" aria-label="发送消息">
            <span id="button-text">发送</span>
            <span id="loading-spinner" class="loading-spinner" aria-hidden="true"></span>
        </button>
    </div>

    <script>
        const chatContainer = document.getElementById('chat-container');
        const messageInput = document.getElementById('message-input');
        const modeSelect = document.getElementById('mode-select');
        const sendButton = document.getElementById('send-button');

        function appendMessage(message, isUser, status) {
            const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser? 'user-message' : 'ai-message'}`;
            messageDiv.innerHTML = `
                <div class="message-content">${message}</div>
                <div class="message-time">${time}</div>
            `;
            // // chatContainer.appendChild(messageDiv);
            // if (chatContainer.children.length > 0) {
            //     console.log(messageDiv, chatContainer.children.length, chatContainer.children[chatContainer.children.length - 1].className === 'message ai-message', 'chatContainer.children.length');
            // }
            if (status === 'error') {
                chatContainer.appendChild(messageDiv);
            } else {
                // 将messageDiv赋值给chatContainer的最后一个子元素
                if (chatContainer.children.length > 0 && chatContainer.children[chatContainer.children.length - 1].className === 'message ai-message') {
                    chatContainer.children[chatContainer.children.length - 1].innerHTML = messageDiv.innerHTML;
                } else {
                    chatContainer.appendChild(messageDiv);
                }
            }
            
            // chatContainer.lastChild = messageDiv;
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        function appendProducts(products) {
            products.forEach(product => {
                const productDiv = document.createElement('div');
                productDiv.className = 'product';
                productDiv.innerHTML = `
                    <img src="${product.image}" alt="${product.store_name}">
                    <div class="product-info">
                        <h3>${product.store_name}</h3>
                        <p><strong>材质:</strong> ${product.caizhi}</p>
                        <p><strong>关键词:</strong> ${product.keyword}</p>
                    </div>
                `;
                chatContainer.appendChild(productDiv);
            });
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        function sendMessage() {
            const message = messageInput.value.trim();
            if (!message) return;

            sendButton.classList.add('loading');
            appendMessage(message, true);
            messageInput.value = '';
            messageInput.disabled = true;

            const params = new URLSearchParams({
                message: message,
                mode: modeSelect.value
            });
            const eventSource = new EventSource(`/api/chat?${params.toString()}`);

            eventSource.onmessage = function (event) {
                try {
                    const data = JSON.parse(event.data);
                    appendMessage(data.message, false, 'success');
                    if (data.products && data.products.length > 0) {
                        appendProducts(data.products);
                    }
                } catch (error) {
                    console.error('Failed to parse event data:', error);
                }
            };

            eventSource.onerror = function (error) {
                console.log(error, 'error');
                
                appendMessage('抱歉，出现了错误。请稍后再试。', false, 'error');
                eventSource.close();
                sendButton.classList.remove('loading');
                messageInput.disabled = false;
                messageInput.focus();
            };
        }

        // Handle enter key
        const characterCount = document.getElementById('character-count');

        function updateCharacterCount() {
            const length = messageInput.value.length;
            characterCount.textContent = `${length}/200`;
        }

        messageInput.addEventListener('input', updateCharacterCount);
        messageInput.addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // Initialize count
        updateCharacterCount();
    </script>
</body>
</html>